define(['jquery', 'bootstrap', 'backend', 'addtabs', 'table', 'echarts', 'echarts-theme', 'template','form','/assets/addons/kuerp/layui/layui.js'],
    function ($, undefined, Backend, Datatable, Table, Echarts, undefined, Template,Form, Layui) {

        var Controller = {
            index: function () {
                let echartData = {
                    title:'销售回款统计分析',
                    data:{
                        goods_name:[],
                        number:[],
                        price:[]
                    },
                    datelist:{
                        date:[],
                        name:{},
                        data:[]
                    }
                };
                layui.use(['form'], function(){
                    var form = layui.form;
                    // var saleLists = Config.saleLists;
                    // var saleuser = xmSelect.render({
                    //     el: '#sale_user',
                    //     language: 'zn',
                    //     tips: '销售人员',
                    //     paging: true,
                    //     pageSize: 5,
                    //     filterable: true,
                    //     data: saleLists,
                    //     on: {
                    //         change: function(data) {
                    //             console.log('Selected data:', data);
                    //             // 在这里添加你需要执行的逻辑
                    //             getData();
                    //         }
                    //     }
                    // });
                    getData()
                    function getData() {
                        var search = getSearch();
                        return $.ajax({
                            type: 'POST',
                            url: 'kuerp/statistic/collection/index',
                            data: search,
                            dataType: 'json',
                           success: function (data) {
                                echartData = data;
                                setEcharts()
                                setTable()
                           }
                        })
                    }

                    //搜索事件
                    $('#search').on('click', function () {
                        getData()
                    });
                    //切换时间类型
                    form.on('select(times)', function(data){
                        $('#dates').val('')
                        if (data.value !='else') {
                            getData()
                            $('#c_dates').addClass('hide')
                        } else {
                            $('#c_dates').removeClass('hide')
                        }
                    });
                    form.on('select(department_id)', function(data){
                        console.log('change1', data)
                        getData()
                    });
                    $('input[name="dates"]').on('change',function (){
                        getData()
                    })
                    function getSearch() {
                        var search = {};
                        var department_id = $('#department_id').val();
                        if(department_id!=''){
                            search.department_id = department_id;
                        }
                        // var saleuserArr = saleuser.getValue();
                        // var saleuser_id = '';
                        // if(saleuserArr.length>0){
                        //     $(saleuserArr).each(function (k,v) {
                        //         if(saleuser_id===''){
                        //             saleuser_id += v.value;
                        //         }else{
                        //             saleuser_id += ','+v.value;
                        //         }
                        //     })
                        //     search.sale_user = saleuser_id
                        // }
                        
                        var times = $('#times').val();
                        if(times!=''){
                            search.times = times;
                        }
                        var dates = $('#dates').val();
                        if(dates!=''){
                            search.dates = dates;
                        }
                        return search;
                    }
                    function setTable() {
                        layui.use('table', function(){
                            var table = layui.table;
                            var products = echartData.data.name;
                            var numbers = echartData.data.number;
                            var prices = echartData.data.price;
                            var cols = [
                                {
                                field: 'type',
                                title: '类型',
                                minWidth: 120,
                                fixed:'left'
                                // colspan: products.length // 根据产品数量设置colspan
                                }
                            ];
                            
                            products.forEach(function(name, index) {
                                cols.push({field: 'name_'+index, title: name, minWidth: 130});
                            });
                            cols.push({field: 'count', title: '合计', minWidth: 130, fixed:'right'});
                            
                            table.render({
                                elem: '#table',
                                cols: [cols],
                                data: [
                                {
                                    type: '回款金额',
                                    ...products.reduce((acc, _, index) => {
                                        acc['name_'+index] = prices[index];
                                        return acc;
                                    }, {}),
                                    count: echartData.count.price
                                },
                                // {
                                //     type: '订单数量',
                                //     ...products.reduce((acc, _, index) => {
                                //         acc['name_'+index] = numbers[index];
                                //         return acc;
                                //     }, {}),
                                //     count: echartData.count.number
                                // }
                                ]
                            });
                            if (Object.keys(echartData.datelist.data).length>0) {
                                var datecols = [];
                                // First row - dates
                                datecols.push([
                                    {field: 'staff_name', title: '销售员', rowspan: 2, fixed: 'left', minWidth: 120}
                                ]);
                                
                                echartData.datelist.date.forEach(function(date) {
                                    datecols[0].push({
                                        title: date,
                                        colspan: 2,
                                        align: 'center',
                                        minWidth: 200
                                    });
                                });

                                // Add total column
                                // Adjust total column to match height with other columns
                                datecols[0].push({
                                    title: '合计', 
                                    colspan: 2,
                                    align: 'center',
                                    rowspan: 1, // Explicitly set rowspan to 1 to match other columns
                                    fixed: 'right',
                                    minWidth: 200,
                                });

                                // Second row - price and number columns for each date
                                var secondRow = [];
                                echartData.datelist.date.forEach(function(date) {
                                    secondRow.push(
                                        {title: '本月订单', field: date + '_price', minWidth: 100},
                                        {title: '之前订单', field: date + '_number', minWidth: 100}
                                    );
                                });
                                // Add total price and number columns
                                secondRow.push(
                                    {title: '回款金额', field: 'total_price',  rowspan: 1, fixed: 'right', minWidth: 100},
                                    // {title: '之前订单回款', field: 'total_number', rowspan: 1, fixed: 'right', minWidth: 100}
                                );
                                datecols.push(secondRow);

                                // Format data for table
                                var tableData = [];
                                var totalRow = {
                                    staff_name: '合计',
                                    total_price: 0,
                                    total_number: 0
                                };

                                // Initialize date totals in totalRow
                                echartData.datelist.date.forEach(function(date) {
                                    totalRow[date + '_price'] = 0;
                                    totalRow[date + '_number'] = 0;
                                });

                                Object.keys(echartData.datelist.name).forEach(function(goodsCode) {
                                    var rowData = {
                                        staff_name: echartData.datelist.name[goodsCode],
                                        total_price: 0,
                                        total_number: 0
                                    };
                                    
                                    echartData.datelist.date.forEach(function(date) {
                                        var data = echartData.datelist.data[goodsCode][date];
                                        rowData[date + '_price'] = data.current;
                                        rowData[date + '_number'] = data.previous;
                                        rowData.total_price += data.current;
                                        rowData.total_price += data.previous;

                                        // Add to totals
                                        totalRow[date + '_price'] += data.current;
                                        totalRow[date + '_number'] += data.previous;
                                        totalRow.total_price += data.current;
                                        totalRow.total_price += data.previous;
                                    });
                                    
                                    tableData.push(rowData);
                                });

                                // Add total row at the end
                                totalRow.total_price = totalRow.total_price.toFixed(2);
                                tableData.push(totalRow);

                                console.log('tableData',datecols, tableData)
                                table.render({
                                    elem: '#datetable',
                                    cols: datecols,
                                    data: tableData,
                                    page: false,
                                    limit: 10000, // 设置每页显示20条数据
                                    done: function () {
                                        // 该方法用于解决,使用fixed固定列后,行高和其他列不一致的问题
                                        var height = this.elem.next().find(".layui-table-box .layui-table-header tr").height();
                                        this.elem.next().find(".layui-table-fixed-r thead th").height(height - 11);
                                        this.elem.next().find(".layui-table-main tbody tr:last-child,.layui-table-fixed tr:last-child").addClass('layui-table-total').css('font-weight','bold');
                                    }
                                });
                            } else {
                                table.reload('datetable', {
                                    data: []
                                });
                            }
                        });
                    }
                });
                
                function setEcharts() {
                    var myChart2=Echarts.init(document.getElementById('echart'), 'walden');
                    var option2 = {
                        title: {
                            text: echartData.title
                        },
                        color:['#5470C6'],
                        tooltip: {
                            trigger: 'axis',
                            axisPointer: {
                                type: 'shadow'
                            }
                        },
                        grid: {
                            left: '3%',
                            right: '4%',
                            bottom: '3%',
                            containLabel: true
                        },
                        toolbox: {
                            show: true,
                            feature: {
                                dataZoom: {
                                    yAxisIndex: 'none'
                                },
                                dataView: { readOnly: false },
                                magicType: { type: ['line', 'bar'] },
                                restore: {},
                                saveAsImage: {},
                            }
                        },
                        legend: {
                            data: [ '回款金额']
                        },
                        xAxis: {
                            type: 'category',
                            boundaryGap: true,
                            nameRotate:30,
                            axisTick: {
                                alignWithLabel: true
                            },
                            // axisLabel:{
                            //     interval:0
                            // },
                            data: echartData.data.name,
                        },
                        yAxis: [
                            {
                                type: 'value',
                                name: '金额'
                              }
                        ],
                        series: [
                            {
                                name: '回款金额',
                                type: 'bar',
                                // stack: 'Total',
                                barWidth: '30%', // 控制柱状图宽度
                                // label: {
                                //     show: true,
                                //     position: 'top' // 在柱状图上方显示数值
                                // },
                                data:  echartData.data.price
                            },
                            // {
                            //     name: '订单数量',
                            //     type: 'bar',
                            //     // stack: 'Total',
                            //     yAxisIndex: 1,
                            //     barWidth: '30%', // 控制柱状图宽度
                            //     // label: {
                            //     //     show: true,
                            //     //     position: 'top' // 在柱状图上方显示数值
                            //     // },
                            //     data: echartData.data.number
                            // },
                        ]
                    };
                    // 使用刚指定的配置项和数据显示图表。
                    myChart2.setOption(option2);
                }

                Form.events.selectpage($("form"));
                Form.events.daterangepicker($("form"));
            },
            //产品TOP10统计分析
            top: function () {
                var myChart2=Echarts.init(document.getElementById('echart'), 'walden');
                var option2 = {
                    title: {
                        text: Orderdata.data.title
                    },
                    color:['#c23531'],
                    tooltip: {
                        trigger: 'axis',
                        axisPointer: {
                            type: 'shadow'
                        }
                    },
                    grid: {
                        left: '3%',
                        right: '4%',
                        bottom: '3%',
                        containLabel: true
                    },
                    toolbox: {
                        show: true,
                        feature: {
                            dataZoom: {
                                yAxisIndex: 'none'
                            },
                            dataView: { readOnly: false },
                            magicType: { type: ['line', 'bar'] },
                            restore: {},
                            saveAsImage: {}
                        }
                    },
                    legend: {
                        data: [ '数量']
                    },
                    xAxis: {
                        type: 'category',
                        boundaryGap: false,
                        data: Orderdata.data.name,
                        axisLabel: {
                            rotate: 80
                        }
                    },
                    yAxis: {
                        type: 'value'
                    },
                    series: [
                        {
                            name: '数量',
                            type: 'line',
                            stack: 'Total',
                            data:  Orderdata.data.number
                        },

                    ]
                };

                // 使用刚指定的配置项和数据显示图表。
                myChart2.setOption(option2);

                Form.events.selectpage($("form"));
                Form.events.daterangepicker($("form"));
            },
            api: {
                bindevent: function () {
                    
                    Form.api.bindevent($("form[role=form]"))
                }
            }
        };

        return Controller;
    });
